using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RubyController : MonoBehaviour
{
    private Rigidbody2D rigidbody2d;
    public float speed = 3.5f; // Ruby的速度

    // Ruby的生命值
    public int maxHealth = 5; // 最大生命值
    private int currentHealth; // 当前生命值
    public int Health { get { return currentHealth; } }

    // Ruby的无敌时间
    public float timeInvincible = 2.0f; // 无敌时间常量
    private bool isInvicible; // 是否处于无敌时间
    private float invincibleTimer; // 计时器

    // Ruby的动画控制
    private Animator animator;
    private Vector2 lookDirection = new Vector2(0, 1);

    // 子弹预制体
    public GameObject projectilePrefab;

    // 音乐源
    public AudioSource audioSource; // 播放特定音效
    public AudioSource walkAudioSource; // 播放走路音

    // 受伤音效
    public AudioClip playerHit;
    // 攻击音效
    public AudioClip attackSoundClip;
    // 走路音效
    public AudioClip walkSound;

    // Ruby重生的位置
    private Vector3 respawnPosition;

    // Start is called before the first frame update
    private void Start()
    {
        // Application.targetFrameRate = 10; // 改变帧率,一般不用设置默认即可
        rigidbody2d = GetComponent<Rigidbody2D>(); // 获取游戏物体身上的组件
        animator = GetComponent<Animator>();
        // audioSource = GetComponent<AudioSource>();
        respawnPosition = transform.position; // 记录初始位置,用于重生

        currentHealth = maxHealth;
    }

    // Update is called once per frame
    private void Update()
    {
        // 玩家的输入监听
        // 横轴的比例系数: 往左是-1, 往右是1, 不动是0
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");
        Vector2 move = new Vector2(horizontal, vertical);
        // 当前玩家输入的某个轴向值不为0
        if (!Mathf.Approximately(move.x, 0) || !Mathf.Approximately(move.y, 0))
        {
            // lookDirection = move;
            lookDirection.Set(move.x, move.y);
            lookDirection.Normalize(); // 单位化,将值变成1
            if (!walkAudioSource.isPlaying)
            {
                // 播放走路音效
                walkAudioSource.clip = walkSound;
                walkAudioSource.Play();
            }
        }
        else
        {
            walkAudioSource.Stop();
        }

        animator.SetFloat("Look X", lookDirection.x);
        animator.SetFloat("Look Y", lookDirection.y);
        animator.SetFloat("Speed", move.magnitude);

        Vector2 position = transform.position;
        // Ruby的水平方向移动
        //position.x += speed * horizontal * Time.deltaTime;
        // Ruby的垂直方向移动
        //position.y += speed * vertical * Time.deltaTime;
        // transform.position = position;

        // Ruby位置的移动
        position += speed * move * Time.deltaTime;
        rigidbody2d.MovePosition(position); // 通过物理引擎来控制移动,防止抖动

        // 无敌时间计算（Update()中的代码每一帧都会去进行运行）
        if (isInvicible)
        {
            // Time.deltaTime 约为 1 / 60, 即每一帧的时间变化单位
            invincibleTimer -= Time.deltaTime;
            if (invincibleTimer <= 0)
            {
                isInvicible = false;
            }
        }

        // 攻击
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Launch();
        }

        // 检测是否与NPC对话
        if (Input.GetKeyDown(KeyCode.T))
        {
            // 发出射线检测
            RaycastHit2D hit = Physics2D.Raycast(
                rigidbody2d.position + Vector2.up * 0.2f,
                lookDirection,
                1.5f,
                LayerMask.GetMask("Npc"));
            if (hit.collider != null)
            {
                NPCDialog npcDialog = hit.collider.GetComponent<NPCDialog>();
                if (npcDialog != null)
                {
                    npcDialog.DisplayDialog();
                }
                // Debug.Log("当前射线检测碰撞到的游戏物体是：" + hit.collider.gameObject);
            }
        }

    }

    // 修改生命值
    public void ChangeHealth(int amount)
    {
        // 受到伤害
        if (amount < 0)
        {
            if (isInvicible)
            {
                return;
            }
            isInvicible = true;
            invincibleTimer = timeInvincible;
            animator.SetTrigger("Hit"); // 播放被击打动画
            PlaySound(playerHit);
        }
        currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
        // Debug.Log("Ruby的生命值：" + currentHealth + "/" + maxHealth);
        UIHealthBar.instance.setValue(currentHealth / (float)maxHealth);

        // 生命值为0则在初始点复活
        if (currentHealth <= 0)
        {
            Respawn();
        }
    }

    // 发射子弹
    private void Launch()
    {
        // 有任务才可以发射子弹
        if (!UIHealthBar.instance.hasTask)
        {
            return;
        }
        // 子弹并不是一开始在游戏世界中放置的游戏物体,而是在需要发射的时候才会生成
        // 根据预制体来生成子弹实例
        GameObject projectileObject = Instantiate(projectilePrefab,
            rigidbody2d.position + Vector2.up * 0.5f, Quaternion.identity);
        Projectile projectile = projectileObject.GetComponent<Projectile>();
        projectile.Launch(lookDirection, 300);
        animator.SetTrigger("Launch"); // 播放Launch动画
        PlaySound(attackSoundClip); // 播放攻击音效
    }

    // 播放音频
    public void PlaySound(AudioClip audioClip)
    {
        audioSource.PlayOneShot(audioClip);
    }

    private void Respawn()
    {
        ChangeHealth(maxHealth);
        transform.position = respawnPosition;
    }

}